// pages/anxiety/thinking.js
Page({
  data: {
    // 主题配置
    theme: {
      primary: '#007AFF',
      secondary: '#5856D6',
      background: '#F2F2F7',
      text: '#000000',
      textSecondary: '#8E8E93'
    },

    // 思维拆解工具
    thinkingTools: [
      {
        id: 'cognitive_restructuring',
        name: '认知重构',
        icon: 'icon-brain',
        color: '#007AFF',
        description: '识别并改变负面思维模式',
        techniques: [
          {
            id: 'thought_record',
            name: '思维记录',
            duration: '10-15分钟',
            difficulty: 'easy',
            description: '记录并分析负面思维的触发情境、情绪和想法',
            steps: [
              { text: '描述触发情境', duration: 2 },
              { text: '识别情绪反应', duration: 2 },
              { text: '记录自动思维', duration: 3 },
              { text: '评估思维准确性', duration: 4 },
              { text: '寻找平衡观点', duration: 4 }
            ]
          },
          {
            id: 'evidence_examination',
            name: '证据检验',
            duration: '15-20分钟',
            difficulty: 'medium',
            description: '客观分析支持和反对负面想法的证据',
            steps: [
              { text: '明确负面想法', duration: 3 },
              { text: '列举支持证据', duration: 5 },
              { text: '寻找反对证据', duration: 5 },
              { text: '权衡证据强度', duration: 4 },
              { text: '形成平衡结论', duration: 3 }
            ]
          },
          {
            id: 'alternative_thinking',
            name: '替代思维',
            duration: '10-15分钟',
            difficulty: 'medium',
            description: '寻找更积极、现实的思维方式',
            steps: [
              { text: '识别负面思维', duration: 2 },
              { text: '质疑思维合理性', duration: 3 },
              { text: '生成替代想法', duration: 5 },
              { text: '评估替代想法', duration: 3 },
              { text: '练习新思维', duration: 2 }
            ]
          }
        ],
        usageCount: 0
      },
      {
        id: 'problem_solving',
        name: '问题解决',
        icon: 'icon-lightbulb',
        color: '#FF9500',
        description: '系统性分析和解决具体问题',
        techniques: [
          {
            id: 'problem_definition',
            name: '问题定义',
            duration: '8-12分钟',
            difficulty: 'easy',
            description: '清晰定义和分析问题的本质',
            steps: [
              { text: '描述问题现状', duration: 3 },
              { text: '明确理想状态', duration: 2 },
              { text: '识别关键障碍', duration: 4 },
              { text: '评估影响因素', duration: 3 }
            ]
          },
          {
            id: 'solution_brainstorm',
            name: '解决方案头脑风暴',
            duration: '15-20分钟',
            difficulty: 'medium',
            description: '创造性地生成多种解决方案',
            steps: [
              { text: '回顾问题定义', duration: 2 },
              { text: '自由联想解决方案', duration: 8 },
              { text: '扩展和完善想法', duration: 5 },
              { text: '初步筛选方案', duration: 5 }
            ]
          },
          {
            id: 'decision_matrix',
            name: '决策矩阵',
            duration: '20-25分钟',
            difficulty: 'hard',
            description: '系统评估和选择最佳解决方案',
            steps: [
              { text: '确定评估标准', duration: 5 },
              { text: '为标准分配权重', duration: 3 },
              { text: '评分各个方案', duration: 10 },
              { text: '计算综合得分', duration: 4 },
              { text: '选择最佳方案', duration: 3 }
            ]
          }
        ],
        usageCount: 0
      },
      {
        id: 'mindfulness_analysis',
        name: '正念分析',
        icon: 'icon-meditation',
        color: '#34C759',
        description: '以正念的方式观察和分析思维',
        techniques: [
          {
            id: 'thought_observation',
            name: '思维观察',
            duration: '10-15分钟',
            difficulty: 'easy',
            description: '不评判地观察思维的来去',
            steps: [
              { text: '找到舒适姿势', duration: 2 },
              { text: '专注呼吸', duration: 3 },
              { text: '观察思维出现', duration: 5 },
              { text: '标记思维类型', duration: 3 },
              { text: '回归呼吸', duration: 2 }
            ]
          },
          {
            id: 'emotion_labeling',
            name: '情绪标记',
            duration: '8-12分钟',
            difficulty: 'easy',
            description: '准确识别和命名当前情绪',
            steps: [
              { text: '感受身体状态', duration: 3 },
              { text: '识别情绪信号', duration: 3 },
              { text: '为情绪命名', duration: 3 },
              { text: '接纳情绪存在', duration: 3 }
            ]
          },
          {
            id: 'acceptance_practice',
            name: '接纳练习',
            duration: '12-18分钟',
            difficulty: 'medium',
            description: '学会接纳而非抗拒困难情绪',
            steps: [
              { text: '识别抗拒情绪', duration: 3 },
              { text: '观察抗拒的感受', duration: 4 },
              { text: '练习温和接纳', duration: 6 },
              { text: '体验接纳的变化', duration: 5 }
            ]
          }
        ],
        usageCount: 0
      }
    ],

    // 当前状态
    currentTool: null,
    currentTechnique: null,
    currentStep: 0,
    sessionActive: false,
    sessionPaused: false,
    sessionStartTime: null,
    sessionDuration: 0,
    stepStartTime: null,
    stepProgress: 0,

    // 用户输入和记录
    userInputs: {},
    sessionNotes: '',
    insights: [],
    actionPlans: [],

    // 统计数据
    stats: {
      totalSessions: 0,
      totalTime: 0,
      favoriteTools: [],
      recentSessions: [],
      insights: [],
      improvements: []
    },

    // UI状态
    showToolSelector: false,
    showTechniqueDetail: false,
    showSettings: false,
    showStats: false,
    showNoteEditor: false,
    showInsightCapture: false,
    showActionPlan: false,
    showSessionSummary: false,

    // 设置
    settings: {
      autoSave: true,
      reminderEnabled: true,
      guidanceLevel: 'detailed', // basic, detailed, expert
      sessionReminder: 24 // hours
    },

    // 定时器
    stepTimer: null,
    sessionTimer: null,

    // 加载状态
    loading: false
  },

  onLoad(options) {
    this.initTheme();
    this.loadSettings();
    this.loadStats();
    
    // 如果有指定工具，直接显示
    if (options.tool) {
      const tool = this.data.thinkingTools.find(t => t.id === options.tool);
      if (tool) {
        this.setData({ currentTool: tool });
      }
    }
  },

  onUnload() {
    this.clearTimers();
    if (this.data.sessionActive) {
      this.saveSession(false); // 保存未完成的会话
    }
  },

  // 初始化主题
  initTheme() {
    const app = getApp();
    const theme = app.globalData.currentTheme;
    this.setData({ theme });
  },

  // 加载设置
  loadSettings() {
    try {
      const settings = wx.getStorageSync('thinking_settings') || this.data.settings;
      this.setData({ settings });
    } catch (error) {
      console.error('加载设置失败:', error);
    }
  },

  // 加载统计数据
  loadStats() {
    try {
      const stats = wx.getStorageSync('thinking_stats') || this.data.stats;
      this.setData({ stats });
    } catch (error) {
      console.error('加载统计数据失败:', error);
    }
  },

  // 选择工具
  onSelectTool(e) {
    const { tool } = e.currentTarget.dataset;
    this.setData({
      currentTool: tool,
      currentTechnique: null,
      showToolSelector: false
    });
  },

  // 选择技巧
  onSelectTechnique(e) {
    const { technique } = e.currentTarget.dataset;
    this.setData({
      currentTechnique: technique,
      currentStep: 0,
      userInputs: {},
      sessionNotes: '',
      insights: [],
      actionPlans: []
    });
  },

  // 开始会话
  onStartSession() {
    if (!this.data.currentTechnique) return;

    const now = Date.now();
    this.setData({
      sessionActive: true,
      sessionPaused: false,
      sessionStartTime: now,
      stepStartTime: now,
      currentStep: 0,
      stepProgress: 0
    });

    this.startSessionTimer();
    this.startStepTimer();
    this.showStepGuidance();
  },

  // 开始会话计时器
  startSessionTimer() {
    this.data.sessionTimer = setInterval(() => {
      if (!this.data.sessionPaused) {
        const duration = Date.now() - this.data.sessionStartTime;
        this.setData({ sessionDuration: duration });
      }
    }, 1000);
  },

  // 开始步骤计时器
  startStepTimer() {
    const step = this.data.currentTechnique.steps[this.data.currentStep];
    if (!step) return;

    const stepDuration = step.duration * 60 * 1000; // 转换为毫秒
    const startTime = Date.now();
    
    this.data.stepTimer = setInterval(() => {
      if (!this.data.sessionPaused) {
        const elapsed = Date.now() - startTime;
        const progress = Math.min((elapsed / stepDuration) * 100, 100);
        this.setData({ stepProgress: progress });

        if (progress >= 100) {
          this.onNextStep();
        }
      }
    }, 100);
  },

  // 显示步骤指导
  showStepGuidance() {
    const step = this.data.currentTechnique.steps[this.data.currentStep];
    if (!step) return;

    const guidance = this.getStepGuidance(step, this.data.currentTechnique.id);
    
    wx.showModal({
      title: `步骤 ${this.data.currentStep + 1}`,
      content: guidance,
      showCancel: false,
      confirmText: '开始',
      success: () => {
        this.setData({ stepStartTime: Date.now() });
      }
    });
  },

  // 获取步骤指导内容
  getStepGuidance(step, techniqueId) {
    const guidanceMap = {
      'thought_record': {
        0: '请详细描述触发你负面情绪的具体情境，包括时间、地点、人物和事件。',
        1: '识别并记录你在这个情境中的情绪反应，可以是愤怒、焦虑、悲伤等。',
        2: '写下当时脑海中出现的自动思维，不要过滤，如实记录。',
        3: '客观分析这些想法是否准确，有哪些证据支持或反对。',
        4: '尝试寻找更平衡、更现实的观点来替代负面想法。'
      },
      'evidence_examination': {
        0: '清楚地写出你想要检验的负面想法或担忧。',
        1: '列出所有支持这个想法的证据和事实。',
        2: '努力寻找反对这个想法的证据，可以问自己"有什么证据表明这不是真的？"',
        3: '比较支持和反对的证据，评估哪些更有说服力。',
        4: '基于证据分析，形成一个更平衡的结论。'
      },
      'problem_definition': {
        0: '具体描述你面临的问题，避免模糊的表述。',
        1: '想象问题解决后的理想状态是什么样的。',
        2: '识别阻碍你达到理想状态的主要障碍。',
        3: '分析影响这个问题的各种因素，包括内在和外在因素。'
      }
    };

    return guidanceMap[techniqueId]?.[this.data.currentStep] || step.text;
  },

  // 下一步
  onNextStep() {
    clearInterval(this.data.stepTimer);
    
    const nextStep = this.data.currentStep + 1;
    if (nextStep >= this.data.currentTechnique.steps.length) {
      this.completeSession();
      return;
    }

    this.setData({
      currentStep: nextStep,
      stepProgress: 0,
      stepStartTime: Date.now()
    });

    this.startStepTimer();
    this.showStepGuidance();
  },

  // 上一步
  onPrevStep() {
    if (this.data.currentStep <= 0) return;

    clearInterval(this.data.stepTimer);
    
    const prevStep = this.data.currentStep - 1;
    this.setData({
      currentStep: prevStep,
      stepProgress: 0,
      stepStartTime: Date.now()
    });

    this.startStepTimer();
  },

  // 暂停/继续
  onTogglePause() {
    const paused = !this.data.sessionPaused;
    this.setData({ sessionPaused: paused });

    if (paused) {
      wx.showToast({
        title: '已暂停',
        icon: 'none'
      });
    } else {
      wx.showToast({
        title: '继续练习',
        icon: 'none'
      });
    }
  },

  // 停止会话
  onStopSession() {
    wx.showModal({
      title: '确认停止',
      content: '确定要停止当前会话吗？进度将会保存。',
      success: (res) => {
        if (res.confirm) {
          this.stopSession();
        }
      }
    });
  },

  // 停止会话
  stopSession() {
    this.clearTimers();
    this.saveSession(false);
    
    this.setData({
      sessionActive: false,
      sessionPaused: false,
      currentStep: 0,
      stepProgress: 0
    });

    wx.showToast({
      title: '会话已停止',
      icon: 'none'
    });
  },

  // 完成会话
  completeSession() {
    this.clearTimers();
    this.saveSession(true);
    
    this.setData({
      sessionActive: false,
      showSessionSummary: true
    });

    // 更新工具使用次数
    const tools = this.data.thinkingTools.map(tool => {
      if (tool.id === this.data.currentTool.id) {
        return { ...tool, usageCount: tool.usageCount + 1 };
      }
      return tool;
    });
    this.setData({ thinkingTools: tools });
  },

  // 清除定时器
  clearTimers() {
    if (this.data.stepTimer) {
      clearInterval(this.data.stepTimer);
      this.setData({ stepTimer: null });
    }
    if (this.data.sessionTimer) {
      clearInterval(this.data.sessionTimer);
      this.setData({ sessionTimer: null });
    }
  },

  // 保存会话
  saveSession(completed) {
    const session = {
      id: Date.now().toString(),
      toolId: this.data.currentTool.id,
      techniqueId: this.data.currentTechnique.id,
      startTime: this.data.sessionStartTime,
      duration: this.data.sessionDuration,
      completed,
      currentStep: this.data.currentStep,
      userInputs: this.data.userInputs,
      notes: this.data.sessionNotes,
      insights: this.data.insights,
      actionPlans: this.data.actionPlans,
      date: new Date().toISOString().split('T')[0]
    };

    try {
      const sessions = wx.getStorageSync('thinking_sessions') || [];
      sessions.unshift(session);
      
      // 只保留最近50个会话
      if (sessions.length > 50) {
        sessions.splice(50);
      }
      
      wx.setStorageSync('thinking_sessions', sessions);
      
      // 更新统计数据
      this.updateStats(session);
    } catch (error) {
      console.error('保存会话失败:', error);
    }
  },

  // 更新统计数据
  updateStats(session) {
    const stats = { ...this.data.stats };
    
    stats.totalSessions += 1;
    stats.totalTime += session.duration;
    
    // 更新最近会话
    stats.recentSessions.unshift({
      date: session.date,
      tool: this.data.currentTool.name,
      technique: this.data.currentTechnique.name,
      duration: session.duration,
      completed: session.completed
    });
    
    if (stats.recentSessions.length > 10) {
      stats.recentSessions.splice(10);
    }
    
    // 更新收藏工具
    const toolIndex = stats.favoriteTools.findIndex(t => t.id === this.data.currentTool.id);
    if (toolIndex >= 0) {
      stats.favoriteTools[toolIndex].count += 1;
    } else {
      stats.favoriteTools.push({
        id: this.data.currentTool.id,
        name: this.data.currentTool.name,
        count: 1
      });
    }
    
    // 按使用次数排序
    stats.favoriteTools.sort((a, b) => b.count - a.count);
    
    this.setData({ stats });
    
    try {
      wx.setStorageSync('thinking_stats', stats);
    } catch (error) {
      console.error('保存统计数据失败:', error);
    }
  },

  // 添加笔记
  onAddNote() {
    this.setData({ showNoteEditor: true });
  },

  // 保存笔记
  onSaveNote(e) {
    const { value } = e.detail;
    this.setData({
      sessionNotes: value,
      showNoteEditor: false
    });
    
    if (this.data.settings.autoSave) {
      this.saveSession(false);
    }
  },

  // 捕获洞察
  onCaptureInsight() {
    this.setData({ showInsightCapture: true });
  },

  // 保存洞察
  onSaveInsight(e) {
    const { value } = e.detail;
    const insights = [...this.data.insights, {
      id: Date.now().toString(),
      content: value,
      timestamp: Date.now(),
      step: this.data.currentStep
    }];
    
    this.setData({
      insights,
      showInsightCapture: false
    });
  },

  // 制定行动计划
  onCreateActionPlan() {
    this.setData({ showActionPlan: true });
  },

  // 保存行动计划
  onSaveActionPlan(e) {
    const { value } = e.detail;
    const actionPlans = [...this.data.actionPlans, {
      id: Date.now().toString(),
      content: value,
      timestamp: Date.now(),
      completed: false
    }];
    
    this.setData({
      actionPlans,
      showActionPlan: false
    });
  },

  // 显示工具选择器
  onShowToolSelector() {
    this.setData({ showToolSelector: true });
  },

  // 显示技巧详情
  onShowTechniqueDetail(e) {
    const { technique } = e.currentTarget.dataset;
    this.setData({
      selectedTechnique: technique,
      showTechniqueDetail: true
    });
  },

  // 显示设置
  onShowSettings() {
    this.setData({ showSettings: true });
  },

  // 显示统计
  onShowStats() {
    this.setData({ showStats: true });
  },

  // 切换设置
  onToggleSetting(e) {
    const { setting } = e.currentTarget.dataset;
    const settings = { ...this.data.settings };
    settings[setting] = !settings[setting];
    
    this.setData({ settings });
    
    try {
      wx.setStorageSync('thinking_settings', settings);
    } catch (error) {
      console.error('保存设置失败:', error);
    }
  },

  // 关闭弹窗
  onCloseModal() {
    this.setData({
      showToolSelector: false,
      showTechniqueDetail: false,
      showSettings: false,
      showStats: false,
      showNoteEditor: false,
      showInsightCapture: false,
      showActionPlan: false,
      showSessionSummary: false
    });
  },

  // 格式化时间
  formatTime(ms) {
    const seconds = Math.floor(ms / 1000);
    const minutes = Math.floor(seconds / 60);
    const hours = Math.floor(minutes / 60);
    
    if (hours > 0) {
      return `${hours}:${(minutes % 60).toString().padStart(2, '0')}:${(seconds % 60).toString().padStart(2, '0')}`;
    } else {
      return `${minutes}:${(seconds % 60).toString().padStart(2, '0')}`;
    }
  },

  // 获取进度百分比
  getProgress() {
    if (!this.data.currentTechnique) return 0;
    const totalSteps = this.data.currentTechnique.steps.length;
    const currentStep = this.data.currentStep;
    const stepProgress = this.data.stepProgress / 100;
    
    return ((currentStep + stepProgress) / totalSteps) * 100;
  },

  // 获取难度文本
  getDifficultyText(difficulty) {
    const map = {
      easy: '简单',
      medium: '中等',
      hard: '困难'
    };
    return map[difficulty] || difficulty;
  },

  // 获取难度颜色
  getDifficultyColor(difficulty) {
    const map = {
      easy: '#34C759',
      medium: '#FF9500',
      hard: '#FF3B30'
    };
    return map[difficulty] || '#8E8E93';
  },

  // 分享功能
  onShareAppMessage() {
    return {
      title: '思维拆解 - 科学管理焦虑情绪',
      path: '/pages/anxiety/thinking',
      imageUrl: '/images/share/thinking.png'
    };
  }
});